<template>
  <div>
    <div class="filter-container" style="margin-left: 20%">
      <el-button icon="el-icon-plus" @click="handerCreate" type="primary">{{$t('添加')}}</el-button>
      <el-select clearable v-model="listQuery.status" filterable placeholder="请选择">
        <el-option
          value="1">
          <span style="float: left;">
           <i class="el-icon-top">{{$t('已上架')}}</i>
          </span>
        </el-option>
        <el-option
          value="0">
          <span style="float: left;">
           <i class="el-icon-bottom">{{$t('已下架')}}</i>
          </span>
        </el-option>
      </el-select>
      <el-input placeholder="请输入策略名称搜索" v-model="listQuery.name" class="input-with-select">
        <el-button slot="append" @click="getList" icon="el-icon-search">{{$t('搜索')}}</el-button>
      </el-input>

    </div>
    <el-table
      :data="list"
      :header-cell-style="{background:'#2f333a',color:'#ffffff',top:'5px','font-size':'15px'}"
      stripe
      style="width: 98%;margin: auto">
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column prop="id" label="编号" width="250">
      </el-table-column>
      <el-table-column prop="name" label="名称" width="150">
        <template slot-scope="scope">
          <el-link :type="scope.row.status==0?'danger':'success'" :underline="false">{{scope.row.name}}</el-link>
        </template>
      </el-table-column>
      <el-table-column align="center" property="iconUrl" width="250" :label="$t('Picture')">
        <template slot-scope="scope">
          <el-popover placement="right" trigger="hover">
            <el-image style="width: 400px;border-radius: 5px" :src="scope.row.pictureUrl" fit="contain"></el-image>
          <el-image slot="reference" preview-src-list style="border-radius:5%;width:100px" :src="scope.row.pictureUrl" lazy>
            <div slot="error" class="image-slot">
              <svg-icon icon-class="youhuiquan-2" style="color: #606266;font-size: 60px"/>
            </div>
          </el-image>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        prop="descr"
        width="450"
        :label="$t('描述')">
        <template slot="header" slot-scope="{row}">
          <i class="el-icon-edit-outline"></i>
          {{$t('描述')}}
        </template>
        <template slot-scope="scope">
         {{scope.row.descr}}
        </template>
      </el-table-column>
      <el-table-column>
        <template slot="header" slot-scope="{row}">
          <i class="el-icon-edit-outline"></i>
          {{$t('状态')}}
        </template>
        <template slot-scope="scope">
          <el-tag :type="scope.row.status==0?'danger':'success'" effect="dark">
            <i :class="scope.row.status==0?'el-icon-sort-down':'el-icon-sort-up'">{{scope.row.status==0?$t('已下架'): $t('已上架') }}</i>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('操作')"
        fixed="right"
        width="180">
        <template slot="header" slot-scope="{row}">
          {{$t('Operate')}}
          <i class="el-icon-setting" style="color: #d35e32"></i>
        </template>
        <template slot-scope="scope">
          <el-link :underline="false" type="primary" @click="handerEdit(scope.row)" size="small"><i class="el-icon-edit"></i>{{$t('编辑')}}</el-link>
          <el-link :underline="false" type="success" @click="handerStatus(scope.row)" size="small"><i class="el-icon-sort"></i>{{scope.row.status==1?$t('下架'):$t('上架')}}</el-link>
          <el-link :underline="false" type="danger" @click="handerDelete(scope.row)" size="small"><i class="el-icon-delete"></i>{{$t('删除')}}</el-link>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList" />
    <dic class="dialogCenter">
      <el-dialog
        :title="dialogStatus=='update'?$t('编辑'):$t('添加')"
        :visible.sync="dialogVisible"
        width="40%"
        :before-close="handleClose">
        <div>
          <el-form :model="couponForm" :rules="rules" ref="couponForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="名称" prop="name">
              <el-input type="textarea"  :autosize="{ minRows: 1}" v-model="couponForm.name"></el-input>
            </el-form-item>
            <el-form-item label="图片" prop="name">
              <el-upload
                class="avatar-uploader"
                accept=".png,.jpg,.jpge,.gif"
                :action="uploadPath"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-success="uploadSuccess">
                <el-image
                  v-if="imageUrlIsShow"
                  :style="{'width':'80%','border-radius':'10px'}"
                  :src="this.couponForm.pictureUrl"
                  class="avatar"
                  fit="contain">
                </el-image>
                <el-progress  v-if="progressIsShow" type="circle" :percentage="parseInt(fake.progress*100)"></el-progress>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="描述" prop="describe">
              <el-input type="textarea":autosize="{ minRows: 2}" v-model="couponForm.descr"></el-input>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-switch
                v-model="couponForm.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="上架"
                inactive-text="下架">
              </el-switch>
            </el-form-item>
            <el-form-item>
              <el-button v-if="dialogStatus=='create'" icon="el-icon-check" type="primary" @click="submitForm('couponForm')">立即创建</el-button>
              <el-button v-else type="primary" plain1 icon="el-icon-edit" @click="editCoupon">提交编辑</el-button>
              <el-button icon="el-icon-refresh" @click="resetForm('couponForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </dic>
  </div>
</template>
<script>
import FakeProgress from 'fake-progress'
import { uploadPath } from '@/api/storage'
import { addCoupon ,coupons ,editCoupon ,statusCoupon,removeCoupon} from '@/api/coupon1'
import Pagination from '@/components/Pagination'
import {getToken} from "../../utils/auth"; // Secondary package based on el-pagination
export default {
  name: "allCoupon",
  components: { Pagination },
  data() {
    return {
      fake:undefined,
      progressIsShow:false,
      imageUrlIsShow:false,
      uploadPath,
      cropperSrc: '', // 待裁剪的图片路径
      dialogStatus:'',
      dialogVisible:false,
      couponForm:{
        name:'',
        status:true,
        pictureUrl:'',
        descr:''
      },
      list: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: 20,
        name: '',
        status: ''
      },
      value: true,
      currentDate: new Date(),
      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 1, max: 255, message: '长度在 1 到 255 个字符', trigger: 'blur' }
        ],
        descr: [
          { required: true, message: '请填写活动形式', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    editCoupon() {
      const data=this.couponForm
      data.status=data.status?1:0
      editCoupon(data).then(res=>{
        this.dialogVisible=false
        this.$notify({
          title: '成功',
          message: '编辑成功',
          type: 'success'
        });
        this.getList()
      }).catch(() => {
        this.$notify.error({
          title: '错误',
          message: '编辑失败'
        });
      })
    },
    getList(){
      coupons(this.listQuery).then(res=>{
        console.log(res)
        this.list=res.data.data.list
        this.total=res.data.data.total
      }).catch(() => {
        this.list=[]
        this.total=0
      })
    },
    handerDelete(row){
      if(row.status==1){
        this.$notify({
          title: '警告',
          message: '该券已上架！',
          type: 'warning'
        });
        return
      }
      this.$confirm('确认删除？')
        .then(_ => {
          removeCoupon(row).then(res=>{
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success'
            });
            this.getList()
          }).catch((res) => {
            if(res.data.errno==401){
              this.$notify({
                title: '警告',
                message: '策略正在使用！',
                type: 'warning'
              });
              return
            }
            this.$notify.error({
              title: '错误',
              message: '删除失败'
            });
          })
        })
        .catch(_ => {});
    },
    handerStatus(row){
      statusCoupon(row).then(res=>{
        this.dialogVisible=false
        if(row.status==1){
          this.$notify({
            title: '成功',
            message: '下架成功',
            type: 'success'
          });
        }else {
          this.$notify({
            title: '成功',
            message: '上架成功',
            type: 'success'
          });
        }
        row.status=row.status==1?0:1
      }).catch((res) => {
        console.log('返回'+res.data.errno)
        if(res.data.errno==202){
          this.$notify({
            title: '警告',
            message: '该券已存在开启的策略中',
            type: 'warning'
          });
        }else{
          this.$notify.error({
            title: '错误',
            message: '上架失败'
          });
        }
        this.getList()
      })
    },
    handerCreate(){
      this.dialogVisible=true
      this.dialogStatus='create'
      this.imageUrlIsShow=false
      this.couponForm={}
    },
    handerEdit(row){
      this.dialogVisible=true
      this.dialogStatus='update'
      this.couponForm=row
      this.couponForm.status=row.status==1
      if(this.couponForm.pictureUrl!=undefined){
        this.imageUrlIsShow=true
      }else {this.imageUrlIsShow=false}
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.getList()
          done();
        })
        .catch(_ => {});
      },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.couponForm.status=this.couponForm.status==false?0:1;
          console.log(this.couponForm);
          addCoupon(this.couponForm).then(res=>{
            if(res.data.data==100){
              this.$notify({
                title: '警告',
                message: '这是一条警告的提示消息',
                type: 'warning'
              });
            }else {
              this.dialogVisible=false
              this.$notify({
                title: '成功',
                message: '这是一条成功的提示消息',
                type: 'success'
              });
              this.$refs['couponForm'].resetFields();
              this.getList()
            }
          })
          .catch(() => {
            this.$notify.error({
              title: '错误',
              message: '创建失败'
            });
          })
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.couponForm={}
    },

    uploadSuccess(response) {
      this.fake.end()
      this.$notify({
        title: '成功',
        message: '上传成功',
        type: 'success'
      });
      this.waitForOneSecond().then(()=>{
        this.progressIsShow=false
        this.imageUrlIsShow=true
        this.couponForm.pictureUrl=response.data.url
      })
    },
    beforeAvatarUpload(file) {
      this.imageUrlIsShow=false
      this.fake=new FakeProgress({
        timeConstant : 900,
        autoStart : true
      }),
      this.progressIsShow=true
      this.fake.autoStart=true
    },
    async waitForOneSecond() {
      await new Promise((resolve) => {
        setTimeout(resolve, 300);
      });
    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  }

}
</script>

<style scoped>
.input-with-select {
  margin: 20px 0px;
  width: 300px;
  transition: all 0.3s;
}



</style>
